﻿namespace Neovolve.Extensibility.ReSharper
{
    using System;
    using JetBrains.DocumentModel;
    using JetBrains.ProjectModel;
    using JetBrains.ReSharper.Psi;
    using JetBrains.ReSharper.Psi.Tree;
    using JetBrains.Util;

    /// <summary>
    /// The <see cref="Extensions"/>
    ///   class is used to provide extension methods to the assembly.
    /// </summary>
    internal static class Extensions
    {
        /// <summary>
        /// Gets the document range.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <returns>
        /// A <see cref="DocumentRange"/> instance.
        /// </returns>
        public static DocumentRange GetDocumentRange(this IElement element)
        {
            return element.GetDocumentRange(0, 0);
        }

        /// <summary>
        /// Gets the document range.
        /// </summary>
        /// <param name="element">
        /// The element.
        /// </param>
        /// <param name="startShift">
        /// The start shift added to the element start offset relative to the document.
        /// </param>
        /// <param name="endShift">
        /// The end shift subtracted from the element end offset relative to the document.
        /// </param>
        /// <returns>
        /// A <see cref="DocumentRange"/> instance.
        /// </returns>
        public static DocumentRange GetDocumentRange(this IElement element, Int32 startShift, Int32 endShift)
        {
            IProjectFile projectItem = element.GetProjectFile();

            if (projectItem == null)
            {
                return DocumentRange.InvalidRange;
            }

            TreeTextRange treeTextRange = element.GetTreeTextRange();
            TextRange textRange = new TextRange(treeTextRange.StartOffset.Offset + startShift, treeTextRange.EndOffset.Offset - endShift);
            DocumentRange range = new DocumentRange(projectItem, textRange);

            return range;
        }
    }
}